const { app, BrowserWindow, ipcMain, dialog } = require('electron');
const path = require('path');
const fs = require('fs');

// 导入业务模块
const AIService = require('./main/ai-service');
const DocumentExporter = require('./main/document-exporter');
const DatabaseManager = require('./main/database-manager');

let mainWindow;
let aiService;
let documentExporter;
let dbManager;

function createWindow() {
  mainWindow = new BrowserWindow({
    width: 1200,
    height: 800,
    webPreferences: {
      nodeIntegration: true,
      contextIsolation: false,
      enableRemoteModule: true
    },
    icon: path.join(__dirname, '../assets/icon.png'),
    show: false
  });

  mainWindow.loadFile('src/renderer/index.html');

  // 开发模式下打开开发者工具
  if (process.argv.includes('--dev')) {
    mainWindow.webContents.openDevTools();
  }

  mainWindow.once('ready-to-show', () => {
    mainWindow.show();
  });

  mainWindow.on('closed', () => {
    mainWindow = null;
  });
}

app.whenReady().then(() => {
  createWindow();
  
  // 初始化服务
  aiService = new AIService();
  documentExporter = new DocumentExporter();
  dbManager = new DatabaseManager();
  
  // 初始化数据库
  dbManager.initialize();

  app.on('activate', () => {
    if (BrowserWindow.getAllWindows().length === 0) {
      createWindow();
    }
  });
});

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit();
  }
});

// IPC 事件处理
ipcMain.handle('generate-topics', async (event, preferences) => {
  try {
    return await aiService.generateTopics(preferences);
  } catch (error) {
    console.error('生成主题失败:', error);
    throw error;
  }
});

ipcMain.handle('generate-article', async (event, topic, options) => {
  try {
    return await aiService.generateArticle(topic, options);
  } catch (error) {
    console.error('生成文章失败:', error);
    throw error;
  }
});

ipcMain.handle('export-to-word', async (event, content, filename) => {
  try {
    const result = await dialog.showSaveDialog(mainWindow, {
      title: '保存Word文档',
      defaultPath: filename || '技术文章.docx',
      filters: [
        { name: 'Word文档', extensions: ['docx'] }
      ]
    });

    if (!result.canceled) {
      await documentExporter.exportToWord(content, result.filePath);
      return { success: true, filePath: result.filePath };
    }
    return { success: false, canceled: true };
  } catch (error) {
    console.error('导出Word失败:', error);
    throw error;
  }
});

ipcMain.handle('save-article', async (event, article) => {
  try {
    return await dbManager.saveArticle(article);
  } catch (error) {
    console.error('保存文章失败:', error);
    throw error;
  }
});

ipcMain.handle('get-article-history', async (event, limit = 50) => {
  try {
    return await dbManager.getArticleHistory(limit);
  } catch (error) {
    console.error('获取历史记录失败:', error);
    throw error;
  }
});

ipcMain.handle('get-settings', async () => {
  try {
    return await dbManager.getSettings();
  } catch (error) {
    console.error('获取设置失败:', error);
    throw error;
  }
});

ipcMain.handle('save-settings', async (event, settings) => {
  try {
    // 更新AI服务配置
    if (settings.ai_provider && settings.api_key) {
      aiService.setApiConfig(settings.ai_provider, settings.api_key, settings.api_base_url);
    }
    return await dbManager.saveSettings(settings);
  } catch (error) {
    console.error('保存设置失败:', error);
    throw error;
  }
});

ipcMain.handle('get-topics', async (event, limit = 20) => {
  try {
    return await dbManager.getTopics(limit);
  } catch (error) {
    console.error('获取主题失败:', error);
    throw error;
  }
});

ipcMain.handle('save-topic', async (event, topic) => {
  try {
    return await dbManager.saveTopic(topic);
  } catch (error) {
    console.error('保存主题失败:', error);
    throw error;
  }
});

ipcMain.handle('get-article-by-id', async (event, id) => {
  try {
    return await dbManager.getArticleById(id);
  } catch (error) {
    console.error('获取文章失败:', error);
    throw error;
  }
});

ipcMain.handle('delete-article', async (event, id) => {
  try {
    return await dbManager.deleteArticle(id);
  } catch (error) {
    console.error('删除文章失败:', error);
    throw error;
  }
});